package com.wangmei.service.serviceimpl;

import com.wangmei.mapper.ProductMapper;
import com.wangmei.mapper.UsercollectionMapper;
import com.wangmei.model.Product;
import com.wangmei.model.UserExample;
import com.wangmei.model.Usercollection;
import com.wangmei.model.UsercollectionExample;
import com.wangmei.service.CollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CollectionServiceImpl implements CollectionService {
    @Autowired
    private UsercollectionMapper usercollectionMapper;
    @Autowired
    private ProductMapper productMapper;
    @Override
    public List<Product> getMyCollection(int uid) {
        Map<String,Object> map = new HashMap<>();
        map.put("uid",uid);
        return usercollectionMapper.selectMyCollection(map);
    }

    @Override
    public int changeType(int uid, int pid) {
        UsercollectionExample example = new UsercollectionExample();
        example.or().andUidEqualTo(uid).andPidEqualTo(pid);
        List<Usercollection> ucs = usercollectionMapper.selectByExample(example);
        if(ucs == null || ucs.size() == 0)
            return addToCollection(uid,pid);
        else
            return cancleCollect(uid,pid);

    }


    private int addToCollection(int uid, int pid) {
        Usercollection record = new Usercollection();
        record.setUid(uid);
        record.setPid(pid);
        record.setIscollect(1);
        usercollectionMapper.insertSelective(record);
        change(pid,1);
        return 1;

    }


    private int cancleCollect(int uid, int pid) {
        UsercollectionExample example = new UsercollectionExample();
        example.or().andUidEqualTo(uid).andPidEqualTo(pid);
        change(pid,-1);
        usercollectionMapper.deleteByExample(example);
        return 0;
    }

    private void change(int pid,int num){
        Product product = productMapper.selectByPrimaryKey(pid);
        if(product!=null){
            product.setPheart(product.getPheart()+num);
            productMapper.updateByPrimaryKeySelective(product);
            }
    }

}

